package com.hyg.module_report.ui.fragment;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.hyg.lib_base.MyView.BodyConstitutionPoint;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.DataModel.ReceiveData;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.module_report.R;
import com.hyg.module_report.adapter.InfoExplainAdapter;
import com.hyg.module_report.adapter.V2MaiXingAdapter;
import com.hyg.module_report.databinding.FragmentReportV2DetailBinding;
import com.hyg.module_report.model.PulseAnalyze;
import com.hyg.module_report.model.V2PulseData;
import com.hyg.module_report.model.V2TiZhiDetailData;
import com.hyg.module_report.model.V2TizhiData;
import com.hyg.module_report.model.V2TongueData;
import com.hyg.module_report.model.V2ZhengXingDetailData;
import com.hyg.module_report.ui.activity.HealthReportV2Activity;


import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;

import static android.view.View.GONE;

public class ReportV2DetailFragment extends Fragment {
    HealthReportV2Activity Activity;
    private MyHandler myHandler;
    FragmentReportV2DetailBinding binding;
    boolean hasHealthData = false;
    boolean hasTongueData = false;
    boolean hasPulseData = false;
    boolean hasTizhiData = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
//      return inflater.inflate(R.layout.fragment_report_v2_detail, container, false);
        binding = FragmentReportV2DetailBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onStart() {
        super.onStart();
        init();
    }

    public void init() {
        Activity = (HealthReportV2Activity) getActivity();
        myHandler = new MyHandler(getActivity());
        getReportDetailData();
    }


    public void getHealthData(String id) {
        {
            String str_tag = "2";
            FormBody formBody = new FormBody.Builder()
                    .add("id", id)//设置参数名称和参数值
                    .build();
            Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getV2ReportHealthData);
        }
    }


    public void getTongue(String id) {
        {
            String str_tag = "4";
            FormBody formBody = new FormBody.Builder()
                    .add("id", id)//设置参数名称和参数值
                    .build();
            Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getV2ReportTongueData);
        }
    }

    public void getPulse(String id) {
        Log.i("lgb", "getPulse: " + id);

        String str_tag = "5";
        FormBody formBody = new FormBody.Builder()
                .add("id", id)//设置参数名称和参数值

                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getV2ReportPulseData);

    }

    public void getTiZhi(String id) {
        String str_tag = "6";
        FormBody formBody = new FormBody.Builder()
                .add("id", id)//设置参数名称和参数值
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getV2ReportBodyData);
    }

    /**
     * description: 查询报告和建议 详细信息
     *
     * @author visitant
     * @time 2020/12/10 10:19
     */
    public void getReportDetailData() {
        getHealthData(Activity.reportListData.getDetailData().getZhengXingId() + "");               //健康评估
        getTongue(Activity.reportListData.getDetailData().getTongueId() + "");              //望诊数据
        getPulse(Activity.reportListData.getDetailData().getPulseId() + "");            //脉枕数据
        getTiZhi(Activity.reportListData.getDetailData().getTiZhiId() + "");            //体质数据
    }

    private class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private HealthReportV2Activity activity;

        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (HealthReportV2Activity) reference.get();
        }

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://查询报告id，是否有此报告
                    break;
                case 2: //解析健康信息并显示
                    ReceiveData receiveData = JSONObject.parseObject(msg.obj.toString(), ReceiveData.class);
                    Log.i("lgb", "handleMessage   ZhengXing==: " + receiveData.toString());
                    showZhengXingView(receiveData);
                    hasHealthData = true;
                    sendEmptyMessage(100);
                    break;
                case 3: //查询结果汇总（目前使用what= 4 5 6 代替）
                    break;
                case 4:// 查询望诊评估
                    ReceiveData receiveData2 = JSONObject.parseObject(msg.obj.toString(), ReceiveData.class);
                    showTongueView(receiveData2);
                    hasTongueData = true;
                    sendEmptyMessage(100);
                    break;
                case 5://查询脉诊评估
                    ReceiveData receiveData3 = JSONObject.parseObject(msg.obj.toString(), ReceiveData.class);
                    Log.i("lgb", "handleMessage   maizhen==: " + receiveData3.toString());
                    showPulseView(receiveData3);
                    hasPulseData = true;
                    sendEmptyMessage(100);
                    break;
                case 6://查询体质评估
                    ReceiveData receiveData4 = JSONObject.parseObject(msg.obj.toString(), ReceiveData.class);
                    showTizhiView(receiveData4);
                    hasTizhiData = true;
                    sendEmptyMessage(100);
                    break;
                case 100://预加载养生建议数据
                    if (hasTizhiData && hasPulseData && hasHealthData && hasTongueData) {
                        activity.updateAdviceData();
                    }
                    break;
                case 101:
                    if (activity.pDialog.isShowing()) {
                        activity.pDialog.dismiss();
                    }
                    break;
            }
        }
    }

    /**
     * description: 显示健康评估view
     *
     * @author visitant
     * @time 2020/12/29 16:54
     */
    public void showZhengXingView(ReceiveData receiveData) {
        if (receiveData.getCode().equals("500")) {
            binding.llZhengxingResult.setVisibility(GONE);
        } else if (receiveData.getCode().equals("200")) {
            V2ZhengXingDetailData data = JSONObject.parseObject(receiveData.getData(), V2ZhengXingDetailData.class);
            if (data == null) {
                binding.llZhengxingResult.setVisibility(GONE);
                return;
            }
            binding.tvUserNameSex.setText("尊敬的" + data.getUserName() + (data.getGender() == 2 ? "女士" : "先生") + "：\n\u3000\u3000您好！欢迎您选择中医体检！\n\u3000\u3000以下为您" + data.getUpdateTime() + "的体检结果，请您认真阅读。");

            V2ZhengXingDetailData.ZhengXingWuxingDTO wuxingDTO = data.getZhengXingWuxing();
            if (wuxingDTO == null) {
                binding.zhengxingWuxing.setVisibility(GONE);
                return;
            } else {
                binding.zhengxingWuxing.setVisibility(View.VISIBLE);
            }
            binding.healthSystem.setData(data.getZhengXingWuxing().getXin(),
                    data.getZhengXingWuxing().getFei(), data.getZhengXingWuxing().getGan(), data.getZhengXingWuxing().getPi(),
                    data.getZhengXingWuxing().getShen(), (data.getGender() == 2 ? "女" : "男"));
            binding.progress.setProgress(data.getZhengXingWuxing().getAvgScore());
            String result = "\u3000\u3000您现";
            if (!Utils.isEmpty(data.getZhengXingWuxing().getSymptomCharacter())) {
                result += "处于：" + data.getZhengXingWuxing().getSymptomCharacter() + " 状态；";
            }
            if (!Utils.isEmpty(data.getZhengXingWuxing().getSymptomLocation()) && !data.getZhengXingWuxing().getSymptomLocation().equals("无")) {
                result += "\n涉及的脏腑为：" + data.getZhengXingWuxing().getSymptomLocation() + " ；";
            }
            if (!Utils.isEmpty(data.getZhengXingWuxing().getZhengXingName())) {
                result += "\n\u3000\u3000提示您目前的健康情况为：" + data.getZhengXingWuxing().getZhengXingName() + "；";
            }
            binding.tvZonghejieguo.setText(result);
        } else {
        }
    }

    /**
     * description: 显示舌象结果
     *
     * @author visitant
     * @time 2020/12/29 17:22
     */
    public void showTongueView(ReceiveData receiveData) {
        if (receiveData.getCode().equals("500")) {
            binding.llShemian.setVisibility(GONE);
        } else if (receiveData.getCode().equals("200")) {
            V2TongueData data = JSONObject.parseObject(receiveData.getData(), V2TongueData.class);
            Glide.with(this).load(data.getSheTuUrl()).error(R.mipmap.tongue_default).into(binding.btStartSheti);
            Glide.with(this).load(data.getMaiLuoUrl()).error(R.mipmap.tongue_default).into(binding.btStartShexia);
            Glide.with(this).load(data.getMianTuUrl()).error(R.mipmap.tongue_default).into(binding.btStartMian);
            binding.btSheshen.setText(data.getSheShen());
            binding.btShese.setText(data.getSheSe());
            binding.btShetai.setText(data.getSheTai4());
            binding.btShexing.setText(data.getSheXing());
            binding.btTaise.setText(data.getSheTai1());
            binding.btTaizhi.setText(data.getTaiZhi());
            binding.shexialuomai.setText(data.getSheXiaLuoMai());
            binding.tvYanseMianbu.setText(data.getMianSe());
            binding.tvGuangzeMianbu.setText(data.getMianBuJieGuo());
            binding.tvColorRenzhong.setText(data.getRenZhongYanSe());
            binding.tvXingtaiRenzhong.setText(data.getRenZhongXingTai());
            if (data.getPulseAnalyze() == null || data.getPulseAnalyze().size() == 0) {
                binding.llWangzhenJieshi.setVisibility(GONE);
            } else {
                LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
                layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                binding.rvShetiJiexi.setLayoutManager(layoutManager);
                InfoExplainAdapter adapter = new InfoExplainAdapter(data.getPulseAnalyze());
                binding.rvShetiJiexi.setAdapter(adapter);
            }
        }
    }

    /**
     * description: 显示体质数据报告
     *
     * @author visitant
     * @time 2020/12/31 11:28
     */
    public void showTizhiView(ReceiveData receiveData) {
        if (receiveData.getCode().equals("500")) {
            binding.llTizhi.setVisibility(GONE);
        } else if (receiveData.getCode().equals("200")) {
            V2TizhiData data = JSONObject.parseObject(receiveData.getData(), V2TizhiData.class);
            binding.btMainConstitution.setText(data.getMajorResult());
            binding.btSecondaryConstitution.setText(data.getMinorResult());
            binding.radarView.setBody(data.getMajorResult(),data.getMinorResult());
            binding.radarView.setData(newGetPoint(data.getAnswer()));

            init_dashuju(data);
            if (data.getPulseAnalyze() == null || data.getPulseAnalyze().size() == 0) {
                binding.llTizhiJiexie.setVisibility(GONE);
            } else {
                LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
                layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                binding.rvTizhiJiexi.setLayoutManager(layoutManager);
                InfoExplainAdapter adapter = new InfoExplainAdapter(data.getPulseAnalyze());
                binding.rvTizhiJiexi.setAdapter(adapter);
            }
        }
    }


    /**
     * description: 显示脉诊数据部分
     *
     * @author visitant
     * @time 2020/12/31 11:27
     */
    public void showPulseView(ReceiveData receiveData) {
        if (receiveData.getCode().equals("500")) {
            binding.llMaizhen.setVisibility(GONE);
        } else if (receiveData.getCode().equals("200")) {

            V2PulseData data = JSONObject.parseObject(receiveData.getData(), V2PulseData.class);
            binding.zonghezhenduan.setText("脉诊综合诊断提示：\n\u3000\u3000" + replaceEnterString(data.getPulseDiagnosis()).replace("\n", "\n\u3000\u3000"));
            binding.tvLeftMaixing.setText("左手脉型:\u3000" + insertMessage(data.getLeftType()));
            binding.tvRightMaixing.setText("右手脉型:\u3000" + insertMessage(data.getRightType()));
            binding.zhenduantishi.setText("最终脉型:\u3000" + data.getFinalPulseType());

            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            binding.RVPulseDatas.setLayoutManager(layoutManager);
            V2MaiXingAdapter adapter = new V2MaiXingAdapter(getActivity(), data.getPulseDataList());
            binding.RVPulseDatas.setAdapter(adapter);
            if (data.getPulseAnalyze() == null || data.getPulseAnalyze().size() == 0) {
                binding.llMaizhenJieshi.setVisibility(GONE);
            } else {
                LinearLayoutManager layoutManager1 = new LinearLayoutManager(getActivity());
                layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
                binding.rvMaizhenJiexi.setLayoutManager(layoutManager1);
//                InfoExplainAdapter adapter1 = new InfoExplainAdapter(data.getPulseAnalyze());
                InfoExplainAdapter adapter1 = new InfoExplainAdapter(getNewList(data.getPulseAnalyze()));
                binding.rvMaizhenJiexi.setAdapter(adapter1);
            }
        }
    }

    /**
     * description: 体质结果图表显示
     *
     * @param
     * @author visitant
     * @time 2020/12/30 11:03
     */
    public ArrayList<BodyConstitutionPoint> newGetPoint(String BCPInfo) {
        ArrayList<BodyConstitutionPoint> _list = new ArrayList<BodyConstitutionPoint>();
        try {
            if (null != BCPInfo && !BCPInfo.equals("null") && !BCPInfo.equals("")) {
                List<V2TiZhiDetailData> list = JSONArray.parseArray(BCPInfo, V2TiZhiDetailData.class);
                for (int i = 0; i < list.size(); i++) {
                    String name = list.get(i).getName();
                    String score = list.get(i).getScore() + "";
                    BodyConstitutionPoint bcp = new BodyConstitutionPoint(
                            "" + name,
                            Double.parseDouble(score),
                            ScroeMeasureMethod(Double.parseDouble(score), list.get(i).getResult().size()),
                            "" + list.get(i).getResult().size(),
                            ""
                    );
                    _list.add(bcp);
                }
            }
        } catch (JSONException e) {
            Log.d("lgb", "" + e.getMessage());
        }
        return _list;
    }

    //计算体质得分方式
    public double ScroeMeasureMethod(double scroe, int itemNumber) {
        double changeScroe = ((scroe - itemNumber) * 100 / (itemNumber * 4));
        return changeScroe;
    }


    /**
     * description: 体质百分比分布
     *
     * @author visitant
     * @time 2020/12/30 11:03
     */
    public void init_dashuju(V2TizhiData data) {
        Float[] datas = {(float) 28.9, (float) 16.4, (float) 5.2, (float) 6.29, (float) 10.2, (float) 13.2, (float) 8, (float) 8.8, (float) 2.5};
        String[] labels = {"平和质", "阳虚质", "阴虚质", "痰湿质", "湿热质", "气虚质", "血瘀质", "气郁质", "特禀质", ""};//标签文本
        String DashujuPhysiqueType = data.getMajorResult() + "。" + data.getMinorResult();
        ArrayList<String> entries = new ArrayList<String>();
        String result = "您的体质辨识结果所在分区如上图所示:\n\u3000\u3000";
        for (int i = 0; i < datas.length; i++) {
            if (DashujuPhysiqueType.contains(labels[i])) {
                String txt = labels[i];// + "\n" + datas[i] + "%";
                entries.add(txt);
                result += labels[i] + "占全部人群体质中的" + datas[i] + "%,";
            } else {
//                entries.add(new PieEntry(datas[i], ""));
            }
        }
        binding.mPercentPieView.setData(entries);
        if (data.getMajorResult().equals("平和质")) {
            binding.dashujuConclusion.setText(result + "\u3000\u3000您是健康的平和体质，您要继续保持自己的健康哦！");
        } else {
            binding.dashujuConclusion.setText(result + "\n\u3000\u3000对比体质检测结果中最棒的平和质，您要为自己的健康加油喽！");
        }

    }


    public static List<PulseAnalyze> getNewList(List<PulseAnalyze> list) {
        List<PulseAnalyze> listTemp = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (listTemp.size() == 0) {
                listTemp.add(list.get(i));
            } else {
                for (int j = 0; j < listTemp.size(); j++) {
                    if (list.get(i).getName().equals(listTemp.get(j).getName())) {
                        break;
                    } else if (j == listTemp.size() - 1) {
                        listTemp.add(list.get(i));
                    }
                }
            }
        }
        return listTemp;
    }


    public String insertMessage(String string) {
        if (TextUtils.isEmpty(string)) {
            return "未测";
        }
        char[] data = string.toCharArray();
        String result = "";
        for (int i = 0; i < data.length; i++) {
            result += data[i] + "脉";
            if (i != data.length - 1) {
                result += "、";
            }
        }
        return result;
    }


    public String replaceEnterString(String string) {
        String result = string;
        while(result.endsWith("\n")) {
            result=result.substring(0,result.length()-2);
        }
        return result;
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        myHandler.removeCallbacksAndMessages(null);
    }
}